package com.ignou.mca.login;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ignou.mca.beans.MailBean;
import com.ignou.mca.datasource.DatabaseOperations;
import com.ignou.mca.utils.MailUtilities;

/**
 * Servlet implementation class UserActivation
 */
public class UserActivation extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserActivation() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String email = request.getParameter("emailID");
		String userName = request.getParameter("userName");
		String activationCode = request.getParameter("activationCode");
		DatabaseOperations dbOperations = new DatabaseOperations();
		ServletContext ctx = getServletContext();
		
		String isActivated = null;
		
		isActivated = dbOperations.doActivation(userName, email, activationCode);
		
		if(isActivated.equalsIgnoreCase("activated"))
		{
			MailBean mb = new MailBean();
			mb.setUserName(userName);
			mb.setEmail(email);
			try {
				MailUtilities.sendMail("useractive", mb);
			} catch (AddressException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			response.sendRedirect("./Login.jsp");
		}else
		{
			request.setAttribute("ErrorMessage", isActivated);
			ctx.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		}
		
	}
}
